package com.example.chatonline.Handler;

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.apache.logging.log4j.message.Message;
import org.springframework.web.socket.WebSocketHandler;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@ServerEndpoint("/WebSocketSever")
public class WebSocketServer {

    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void onOpen(Session session){
        System.out.println("websocket建立连接"+session.getId());
        //将当前session加入在线会话统计中
        sessions.add(session);
    }

    @OnMessage
    public void OnMessage(Session session, Message message) throws IOException {
        System.out.println("收到消息"+message);
        session.getBasicRemote().sendText("Server received: " + message);
    }

    @OnClose
    public void OnClose(Session session){
        System.out.println(session.getId()+"退出连接");
        sessions.remove(session);
    }

    @OnError
    public void OnError(Session session){
        System.out.println("websocket异常");
    }
}
